// @ts-nocheck
import prompt from '@ohos.prompt';
import router from '@ohos.router';
import Bullet from '../../common/js/bullet';
import autoTank from '../../common/js/autoTank';
import {collision} from '../../common/js/collision';

/*
全局变量  getApp().data
myTankDir   我的坦克方向 0上 1 下 2 左 3 右
myTankPos  //我的坦克位置
MAP1         等级1地图
home         // 家的坐标
autoTankArray    //敌方坦克集合
drawMap      //画笔
autoTankNum   //敌方坦克数量
isHomeState //家的状态
mapSource //地图上所有的物体
*/

/**************坦克图片资源*****************/
var MY_TANK_RESOURCE_IMAGE = new Image();
MY_TANK_RESOURCE_IMAGE.src = 'common/images/myTank1.png';

var HOME_RESOURCE_IMAGE = new Image();
HOME_RESOURCE_IMAGE.src = 'common/images/home.png';

var SOFTWALL_RESOURCE_IMAGE = new Image();
SOFTWALL_RESOURCE_IMAGE.src = 'common/images/softWall.png';

var HARDWALL_RESOURCE_IMAGE = new Image();
HARDWALL_RESOURCE_IMAGE.src = 'common/images/hardWall.png';

var TANK_RESOURCE_IMAGE = new Image();
TANK_RESOURCE_IMAGE.src = 'common/images/tank.png';

/**************各个图块在坦克图片资源的位置*****************/
var POS = [];
POS['myTank'] = [0, 0];
var IMAGE_SPACE = 7; //图片之间的间隔
POS['tank'] = [0, 0];

/**************坦克及子弹的四个方向*****************/
var UP = 0;
var DOWN = 1;
var LEFT = 2;
var RIGHT = 3;

/**************子弹类型*****************/
var BULLET_TYPE_PLAYER = 5; //玩家
var BULLET_TYPE_ENEMY = 4; //敌方

export default {
  data: {
    isHomeStateTimer: null, // 检测isHomeState变化
    tankNumTimer: null //检测敌方坦克数量变化
  },

  onInit() {
    //全局变量初始化
    getApp().data.myTankDir = UP;
    getApp().data.isHomeState = true;
    getApp().data.autoTankArray = [];
    getApp().data.autoTankNum = 0;
    getApp().data.drawMap = null;
    for (let i = 0; i < 20; i++) {
      for (let j = 0; j < 14; j++) {
        getApp().data.mapSource[j][i] = getApp().data.MAP1[i][j];
      }
    }
  },

  onShow() {
    this.initMap();
    this.isHomeStateTimer = setInterval(() => {
      this.checkHomeState();
    }, 50);
    this.tankNumTimer = setInterval(() => {
      this.checkTankNum();
    }, 50);
    //console.log('游戏页面打开');
  },

  initMap() { //初始化地图
    let isMap = this.$element('map');
    if (!isMap) {
      return;
    }
    //console.log('成功获取map元素');
    getApp().data.drawMap = isMap.getContext('2d', {
      antialias: true
    })
    for (let i = 0; i < 14; i++) {
      for (let j = 0; j < 20; j++) {
        switch (getApp().data.mapSource[i][j]) {
          case 1:
            getApp().data.drawMap.drawImage(SOFTWALL_RESOURCE_IMAGE, i * 50, j * 50, 50, 50);
            break;
          case 2:
            getApp().data.drawMap.drawImage(HARDWALL_RESOURCE_IMAGE, i * 50, j * 50, 50, 50);
            break;
          case 3:
            getApp().data.drawMap.drawImage(HOME_RESOURCE_IMAGE, i * 50, j * 50, 50, 50);
            break;
          case 4:
            let x = new autoTank([i, j]);
            getApp().data.autoTankNum++;
            getApp().data.autoTankArray.push(x);
            break;
          case 5:
            getApp().data.myTankPos[0] = i;
            getApp().data.myTankPos[1] = j;
            getApp().data.myTankDir = 0;
            getApp().data.drawMap.drawImage(MY_TANK_RESOURCE_IMAGE,
              POS['myTank'][0] + 50 * getApp().data.myTankDir + IMAGE_SPACE,
              POS['myTank'][1], 50, 50, getApp().data.myTankPos[0] * 50, getApp().data.myTankPos[1] * 50, 50, 50);
            break;
        }
      }
    }
    //console.log('敌方坦克的数量' + getApp().data.autoTankArray.length);
    // 坦克启动
    getApp().data.autoTankArray.forEach(item => {
      item.auto();
    })
  },

  // 控制行动
  handleUp() {
    getApp().data.myTankDir = 0; //掉头 上
    this.hanndleMove(1, -1) // (Y坐标，步长)
  },
  handleLeft() {
    getApp().data.myTankDir = 2; //掉头 左
    this.hanndleMove(0, -1) // (X坐标，步长)
  },
  handleRight() {
    getApp().data.myTankDir = 3; //掉头 右
    this.hanndleMove(0, 1) // (X坐标，步长)
  },
  handleDown() {
    getApp().data.myTankDir = 1; //掉头 下
    this.hanndleMove(1, 1) // (Y坐标，步长)
  },
  hanndleMove(posIndex, step) {
    let oldMyTankPos = JSON.parse(JSON.stringify(getApp().data.myTankPos))
    //console.info(oldMyTankPos);
    getApp().data.myTankPos[posIndex] = oldMyTankPos[posIndex] + step;
    switch (collision(getApp().data.myTankPos)) {
      case 0: // 无障碍
        this.Destroy(oldMyTankPos);
        this.Create();
        console.log('坦克在移动');
        break;
      case 1: // softWall
        getApp().data.myTankPos = oldMyTankPos;
        this.Create();
        console.log('子弹撞可击毁墙');
        break;
      case 2: //  hardWall
        getApp().data.myTankPos = oldMyTankPos;
        this.Create();
        console.log('我的坦克撞不可击毁墙');
        break;
      case 3: //home
        getApp().data.myTankPos = oldMyTankPos;
        this.Create();
        console.log('我的坦克撞到家');
        break;
      case 4: // autoTank
        getApp().data.myTankPos = oldMyTankPos;
        this.Create();
        console.log('我的坦克撞到敌方坦克');
        break;
      case 5: // myTank
        break;
      case 6: //myBullet
        break;
      case 7: //bullet 由子弹决定击毁
        break;
      case 8: //border
        getApp().data.myTankPos = oldMyTankPos;
        this.Create();
        console.log('我的坦克撞边界了');
        break;
    }
  },

  // 新建
  Create() {
    getApp().data.drawMap.drawImage(MY_TANK_RESOURCE_IMAGE, POS['myTank'][0] + 50 * getApp().data.myTankDir + IMAGE_SPACE,
      POS['myTank'][1], 50, 50, getApp().data.myTankPos[0] * 50, getApp().data.myTankPos[1] * 50, 50, 50);
    getApp().data.mapSource[getApp().data.myTankPos[0]][getApp().data.myTankPos[1]] = 5; //移动
  },

  //销毁
  Destroy(oldPos) {
    getApp().data.drawMap.clearRect(oldPos[0] * 50, oldPos[1] * 50, 50, 50);
    getApp().data.mapSource[oldPos[0]][oldPos[1]] = 0; //移动
  },

  // 重置按钮
  handleReset() {
    clearInterval(this.isHomeStateTimer);
    clearInterval(this.tankNumTimer);
    //重置之前一定要“释放对象”
    getApp().data.autoTankArray.forEach(item => {
      item.clear();
    });
    router.replace({
      url: 'pages/gamePage/gamePage'
    })
  },
  onDestroy() {
    console.log('消灭' + getApp().data.autoTankArray.length);
    getApp().data.autoTankArray.forEach(item => {
      item.clear();
    })
  },

  //发射子弹
  handleShot() {
    let x = new Bullet(BULLET_TYPE_PLAYER, getApp().data.myTankDir, getApp().data.myTankPos);
    x.run();
  },

  // 检查家存在状态
  checkHomeState() {
    //console.log('时刻检查家状态');
    if (!getApp().data.isHomeState) { //家的位置是否清零
      //所有坦克停下来
      getApp().data.autoTankArray.forEach(item => {
        item.clear();
      });
      clearInterval(this.isHomeStateTimer);
      clearInterval(this.tankNumTimer);
      //console.log('游戏结束');
      this.showFDialog();

    }
  },

  //检查敌方坦克数量
  checkTankNum() {
    if (getApp().data.autoTankNum === 0) {
      getApp().data.autoTankArray.forEach(item => {
        item.clear();
      });
      clearInterval(this.isHomeStateTimer);
      clearInterval(this.tankNumTimer);
      this.showSDialog();
    }
  },

  //游戏失败提示
  showFDialog() {
    prompt.showDialog({
      title: '失败0',
      message: '是否重新开始',
      buttons: [
        {
          text: '确认',
          color: '#000000',
        },
        {
          text: '退出',
          color: '#000000',
        }
      ]
    }, (err, data) => {
      if (data.index === 1) {
        router.replace({
          url: 'pages/index/index'
        })
      } else {
        router.replace({
          url: 'pages/gamePage/gamePage'
        })
      }
    });
  },

  //游戏成功提示
  showSDialog() {
    prompt.showDialog({
      title: '成功0',
      message: '是否进入到下一关',
      buttons: [
        {
          text: '确认',
          color: '#000000',
        },
        {
          text: '取消',
          color: '#000000',
        }
      ]
    }, (err, data) => {
      if (data.index === 0) {
        router.replace({
          url: 'pages/index/index'
        })
      } else {
        router.replace({
          url: 'pages/gamePage/gamePage'
        })
      }
    });
  }
}